<template>
  <div class="GiftManagement">
    <el-card v-loading="loading" class="box-card">
      <!-- id搜索 -->
      <div class="searchBox">
        <div>
          礼物名称：
          <el-input
            v-model="form.name"
            style="width: 200px"
            placeholder="请输入名称"
          ></el-input>
          <span style="margin: 0 20px">
            礼物类型：
            <el-select v-model="type" @change="query" placeholder="请选择">
              <el-option label="不限" value=""></el-option>
              <el-option
                v-for="item in StatusOptions"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              >
              </el-option>
            </el-select>
          </span>
          <el-button @click="query" class="btn">查询</el-button>
        </div>

        <el-button @click="dialogFormVisible = true">新增礼物</el-button>
      </div>
      <el-table v-if="bol" :data="tableData" style="width: 100%">
        <el-table-column label="添加时间" prop="create_time">
          <template slot-scope="scope">
            {{ time(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="ID" width="55" prop="id"></el-table-column>
        <el-table-column label="图标" width="180">
          <template slot-scope="scope">
            <Upload
              type="1"
              :url="scope.row.img_url"
              @change="
                (url) => {
                  imgChang(url, scope.row);
                }
              "
            ></Upload>
          </template>
        </el-table-column>
        <el-table-column label="动画" width="180">
          <template slot-scope="scope">
            <Upload
              v-if="scope.row.type != 2"
              type="2"
              :url="scope.row.dynamic_effect"
              :id="scope.$index"
              @change="
                (url) => {
                  svgaChang(url, scope.row);
                }
              "
            ></Upload>
          </template>
        </el-table-column>
        <el-table-column label="名称" width="180">
          <template slot-scope="scope">
            <el-form ref="form" :model="scope.row">
              <el-form-item>
                <el-input v-model="scope.row.name"></el-input>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="价格">
          <template slot-scope="scope">
            <el-form ref="form" :model="scope.row">
              <el-form-item>
                <el-input
                  v-model="scope.row.price"
                  type="number"
                  min="1"
                  max="10000000"
                  oninput="value=value.replace('-','')"
                ></el-input>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="类型">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type == 1">普通礼物</el-tag>
            <el-tag type="success" v-if="scope.row.type == 2">连送礼物</el-tag>
            <el-tag type="info" v-if="scope.row.type == 3">公告礼物</el-tag>
            <el-tag type="warning" v-if="scope.row.type == 4">每日礼物</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_del"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="toUpdate(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="排序">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.sort"
              type="number"
              oninput="value=value.replace(/[^\d]/g,'')"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="del(scope.row)"
              >删除</el-button
            >
            <el-button size="mini" @click="toUpdate(scope.row)">更新</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        title="新增礼物"
        :visible.sync="dialogFormVisible"
        @close="dialogClose"
      >
        <el-form :model="formDialog">
          <el-form-item label="类型" :label-width="formLabelWidth">
            <el-select
              v-model="formDialog.select"
              placeholder="请选择礼物类型"
              @change="getCouponSelected"
            >
              <el-option
                v-for="item in StatusOptions"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              class="avatar-uploader"
              :http-request="upLoad1"
              :show-file-list="false"
              accept="image/png,image/jpg,image/jpeg"
              action
            >
              <img
                v-if="formDialog.img_url"
                :src="formDialog.img_url"
                class="img"
                style="width: 178px; height: 178px"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon img"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="动画" v-if="formDialog.select != 2">
            <el-upload
              class="avatar-uploader"
              :http-request="upLoad2"
              :show-file-list="false"
              action
            >
              <SvgaIcon
                v-if="formDialog.dynamic_effect"
                :url="formDialog.dynamic_effect"
                :index="'up'"
              ></SvgaIcon>
              <i v-else class="el-icon-plus avatar-uploader-icon img"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="formDialog.name" style="width: 25%"></el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input
              v-model="formDialog.price"
              type="number"
              min="1"
              max="10000000"
              oninput="value=value.replace('-','')"
              style="width: 25%"
            ></el-input>
          </el-form-item>
          <el-form-item label="排序">
            <el-input
              v-model="formDialog.sort"
              type="number"
              min="1"
              max="10000000"
              oninput="value=value.replace('-','')"
              style="width: 25%"
            ></el-input>
          </el-form-item>
        </el-form>

        <div style="margin: 0 auto">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="newlyAdded">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分页 -->
      <!-- v-show="total > 0" -->
      <pagination
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="getGiftList"
      />
    </el-card>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // 分页
import {
  adminGiftManageList,
  adminGiftManageAddGift,
  adminGiftManageDel,
  adminGiftManageEdit,
} from "@/api/operationManagement";
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";
import SvgaIcon from "@/components/PlaySvga";
import Upload from "@/components/UploadImg";
export default {
  components: { Pagination, SvgaIcon, Upload },
  data() {
    return {
      imgUrl: "",
      dhImgurl: "",
      baseImgUrl: "https://img.psychexy.com",
      dialogImageUrl: "",
      dialogImageUrl1: "",
      rowImg: [],
      loading: true,
      StatusOptions: [
        {
          key: 1,
          value: "普通礼物",
        },
        {
          key: 2,
          value: "连送礼物",
        },
        {
          key: 3,
          value: "公告礼物",
        },
        {
          key: 4,
          value: "每日免费礼物",
        },
      ],
      dialogFormVisible: false, //弹框状态
      type: "",
      page: 1,
      pageSize: 10,
      total: 0,
      form: {
        name: "",
      },
      dialogImageUrl: "",
      formDialog: {
        select: "",
        name: "",
        price: "",
        img_url: "",
        dynamic_effect: "",
        sort: "0",
      },
      value: "",
      tableData: [],
      type1: 1,
      bol: true,
    };
  },
  methods: {
    imgChang(url, obj) {
      obj.img_url = url;
      this.toUpdate(obj);
    },
    svgaChang(url, obj) {
      obj.dynamic_effect = url;
      this.toUpdate(obj);
    },
    dialogClose() {
      this.formDialog.select = "";
      this.formDialog.name = "";
      this.formDialog.price = "";
      this.formDialog.img_url = "";
      this.formDialog.dynamic_effect = "";
      this.formDialog.sort = "0";
    },
    // 弹框取消
    cancel() {
      this.dialogFormVisible = false;
      this.formDialog.name = "";
      this.imgUrl = "";
      this.formDialog.price = "";
      this.dhImgurl = "";
    },

    //   弹框确定
    newlyAdded() {
      if (this.formDialog.sort == "") {
        this.$message({
          type: "error",
          message: "排序不能为空！",
        });
        return;
      }
      if (
        this.formDialog.name != "" &&
        this.formDialog.price != "" &&
        this.formDialog.img_url != ""
        // this.formDialog.dynamic_effect != ""&this.formDialog.select
      ) {
        if (this.type1 == 4) {
          adminGiftManageList({
            type: 4,
            page: this.page,
            pageSize: this.pageSize,
          }).then((res) => {
            // console.log(res);
            if (res.data.list.length >= 1) {
              this.$message.error("每日礼物只能有一个");
            } else {
              adminGiftManageAddGift({
                name: this.formDialog.name,
                img_url: this.formDialog.img_url,
                dynamic_effect: this.formDialog.dynamic_effect,
                type: this.type1,
                price: this.formDialog.price,
                sort: this.formDialog.sort,
              }).then((res) => {
                if (res.code == 0) {
                  this.$message({
                    message: "添加成功",
                    type: "success",
                  });
                  this.dialogFormVisible = false;
                  // this.$router.push("/OperationManagement/GiftManagement");
                  this.getGiftList();
                }
              });
            }
          });
        } else {
          adminGiftManageAddGift({
            name: this.formDialog.name,
            img_url: this.formDialog.img_url,
            dynamic_effect: this.formDialog.dynamic_effect,
            type: this.type1,
            price: this.formDialog.price,
            sort: this.formDialog.sort,
          }).then((res) => {
            if (res.code == 0) {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.dialogFormVisible = false;
              // this.$router.push("/OperationManagement/GiftManagement");
              this.getGiftList();
            }
          });
        }
      } else {
        this.$message.error("请输入内容");
      }
    },
    //   动画{}
    handleAvatarSuccess1(res, file) {
      console.log("上传成功", res, file);
      this.dialogImageUrl1 = URL.createObjectURL(file.raw);
      console.log(this.dialogImageUrl1);
      //   this.rowImg.icon = URL.createObjectURL(file.raw);
    },
    handlePictureCardPreview1(file, obj) {
      //   console.log(obj);
      this.dialogImageUrl1 = file.url;
    },
    // 图片
    handleAvatarSuccess(res, file) {
      console.log("上传成功", res, file);
      this.dialogImageUrl = URL.createObjectURL(file.raw);
      console.log(this.dialogImageUrl);
      //   this.rowImg.icon = URL.createObjectURL(file.raw);
    },
    handlePictureCardPreview1(file, obj) {
      //   console.log(obj);
      this.dialogImageUrl = file.url;
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad1(file, obj) {
      //   console.log(obj);
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-" + res.data.regionId,
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      try {
        let fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
        //fileNames上传文件的名称
        //file.file上传文件的内容
        let cli = client(this.dataObj);
        let result = cli.multipartUpload(fileNames, file.file);
        result.then(() => {
          self.formDialog.img_url = "https://img.psychexy.com" + fileNames;
          self.$message({
            message: "上传成功",
            type: "success",
          });
        });
      } catch (e) {
        self.$message.error("上传失败");
      }
    },
    //覆盖默认的上传行为，自定义上传的实现
    async upLoad2(file, obj) {
      //   console.log(obj);
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-" + res.data.regionId,
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      try {
        let fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
        //fileNames上传文件的名称
        //file.file上传文件的内容
        let cli = client(this.dataObj);
        self.dhImgurl = fileNames;

        let result = cli.multipartUpload(fileNames, file.file);
        result.then(() => {
          self.formDialog.dynamic_effect =
            "https://img.psychexy.com" + fileNames;
          self.$message({
            message: "上传成功",
            type: "success",
          });
        });
      } catch (e) {
        self.$message.error("上传失败");
      }
    },
    //下拉框
    getCouponSelected(e) {
      this.type1 = e;
      console.log(e);
    },

    getGiftList() {
      this.tableData = [];
      this.bol = false;
      this.loading = true;
      adminGiftManageList({
        type: this.type,
        page: this.page,
        pageSize: this.pageSize,
        name: this.form.name,
      }).then((res) => {
        console.log(res);
        this.total = res.count;
        res.data.list.forEach((item) => {
          if (item.is_del == "0") {
            item.is_del = true;
          } else if (item.is_del == "2") {
            item.is_del = false;
          }
        });
        this.tableData = res.data.list;
        this.total = parseInt(res.data.count);
        this.loading = false;
        this.bol = true;

        // console.log(this.tableData);
      });
    },
    // 更新
    toUpdate(row) {
      adminGiftManageEdit({
        type: row.type,
        id: row.id,
        name: row.name,
        img_url: row.img_url,
        dynamic_effect: row.dynamic_effect,
        price: row.price,
        is_del: row.is_del ? "0" : "2",
        sort: row.sort,
      }).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: "更新成功",
            type: "success",
          });
          this.getGiftList();
        }
      });
    },
    query() {
      this.page = 1;
      this.getGiftList();
    },
    del(row) {
      adminGiftManageDel({ id: row.id }).then((res) => {
        // console.log(res);
        if (res.code == 0) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getGiftList();
        }
      });
      //   console.log(row);
    },
  },
  created() {
    // this.handleClick();
    this.getGiftList();
    this.formDialog.select = this.StatusOptions[0].key;
  },
  computed: {
    time() {
      return function (date) {
        var date = new Date(date * 1000);
        var YY = date.getFullYear() + "-";
        var MM =
          (date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1) + "-";
        var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hh =
          (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) +
          ":";
        var mm =
          (date.getMinutes() < 10
            ? "0" + date.getMinutes()
            : date.getMinutes()) + ":";
        var ss =
          date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return YY + MM + DD + " " + hh + mm + ss;
      };
    },
  },
};
</script>


<style lang="less" scoped>
.GiftManagement {
  padding: 20px;
  .searchBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.imgFlex {
  display: flex;
  align-items: center;
}
// .tab {
//   display: flex;
//   justify-content: space-between;
// }
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  // min-height: 178px;
}
// /deep/ .avatar-uploader {
//   width: 200px;
//   height: 200px;
//   border: 1px dashed #ccc;
// }
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  //   overflow: hidden;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
// /deep/ .cell {
//   height: px;
// }
</style>